import type { BookingEngineForBooking } from './booking-engine-booking'

/**
 * 引擎注册中心：
 * - 记录当前运行中的预约引擎实例，提供全局“停止预约”能力。
 * - Renderer 通过 IPC 调用 booking:stop，主进程转而调用 cancelAllEngines()。
 * - 简洁实现：用 Set 保存实例；取消时并行调用每个引擎的 cancel()。
 */
const active = new Set<BookingEngineForBooking>()

// 全局批次取消标记：当用户点击“停止预约”时置位，阻止新的任务继续启动
let globalCancelRequested = false

export function registerEngine(engine: BookingEngineForBooking): void {
  active.add(engine)
}

export function unregisterEngine(engine: BookingEngineForBooking): void {
  active.delete(engine)
}

export async function cancelAllEngines(): Promise<void> {
  const tasks: Array<Promise<void>> = []
  for (const e of Array.from(active)) {
    try {
      tasks.push(e.cancel().catch(() => {}))
    }
    catch {}
  }
  await Promise.all(tasks)
}

export function getActiveEngineCount(): number {
  return active.size
}

export function requestGlobalCancel(): void {
  globalCancelRequested = true
}

export function clearGlobalCancel(): void {
  globalCancelRequested = false
}

export function isGlobalCancelRequested(): boolean {
  return globalCancelRequested
}

// 清空注册表（在全局停止后做兜底清理）
export function clearRegistry(): void {
  try { active.clear() }
  catch {}
  globalCancelRequested = false
}
